package com.example.book_recommend.service.impl;

import com.example.book_recommend.dao.*;
import com.example.book_recommend.entity.*;
import com.example.book_recommend.service.CartService;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import java.awt.print.Book;
import java.math.BigDecimal;
import java.util.*;

@Service("CartService")
public class CartServiceImpl implements CartService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    BookInfoMapper bookInfoMapper;
    @Autowired
    CartMapper cartMapper;
    @Autowired
    UserRoleMapper userRoleMapper;
    @Autowired
    OrdersMapper ordersMapper;
    @Autowired
    OrderDetailMapper orderDetailMapper;

    @Override
    public Boolean addBook(int uid, Long bookId, int count) {
        Boolean ifUidExist = false;
        Boolean ifBookExist = false;
        Boolean ifCartExist = false;
        Boolean ifVIP = false;
        User user;
        try {
            user = userMapper.selectByPrimaryKey(uid);
            ifUidExist = true;
        }catch (NullPointerException nullPointerException)
        {
            return false;
        }

        Integer[] userRole = {};
        try {
            userRole = userRoleMapper.getRolesById(uid);
            for (Integer integer : userRole) {
                if (integer == 2) {
                    ifVIP = true;
                    break;
                }
            }
        }catch (NullPointerException nullPointerException){
            ifVIP = false;
        }


        BookInfo bookinfo = new BookInfo();
        try {
            bookinfo = bookInfoMapper.selectByPrimaryKey((long)bookId);
            ifBookExist = true;
        }catch (NullPointerException nullPointerException)
        {
            return false;
        }

        ArrayList<Cart> carts = new ArrayList<>();
        try {
            carts = cartMapper.selectByUid(uid);
            ifCartExist = carts.size() != 0;

        }catch (NullPointerException nullPointerException){
            ifCartExist = false;
        }

        if (ifCartExist){
            //该用户的购物车已经存在
            System.out.println("Cart exist");
            //Step1-购物车内搜索该书籍，若没有，则添加，若有，则添加数量
//            Iterator<Cart> cartIterator = carts.iterator();
//            while (cartIterator.hasNext()){
//                Cart tempCart = cartIterator.next();
//            }
            Boolean bookExist = false;
            for (Cart tempCart : carts) {
                if (tempCart.getBookId().equals(bookId)){
                    System.out.println("book exist");
                    bookExist = true;
                    tempCart.setCount(tempCart.getCount() + count);
                    tempCart.setUpdateTime(new Date());
                    cartMapper.updateByPrimaryKey(tempCart);
                    break;
                }
            }
            if (!bookExist) {
                System.out.println("book do not exist");
                Cart lastCart = cartMapper.selectAll().get(cartMapper.selectAll().size() - 1);
                cartMapper.insert(new Cart(lastCart.getCartId() + 1, uid, bookId, bookinfo.getPrice(),
                        count, new Date(), new Date(), count*bookinfo.getPrice().floatValue()));
            }
        }else {
            // 该用户的购物车暂时不存在, 新建一个最新的购物车
            System.out.println("Cart not exist, build a new one");
            Cart lastCart = cartMapper.selectAll().get(cartMapper.selectAll().size() - 1);
            cartMapper.insert(new Cart(lastCart.getCartId() + 1, uid, bookId, bookinfo.getPrice(),
                    count, new Date(), new Date(), count*bookinfo.getPrice().floatValue()));
        }

        //更新该用户的所有的total
        float total = 0;
        for (Cart eachCart : carts){
            total += eachCart.getCount() * eachCart.getUnitPrice().floatValue();
        }
        for (Cart eachCart : carts){
            eachCart.setTotalMoney(total);
            cartMapper.updateByPrimaryKey(eachCart);
        }

        return true;
    }

    @Override
    public Boolean delBook(int uid, Long bookId, int count) {
        Boolean ifUidExist = false;
        Boolean ifBookExist = false;
        Boolean ifCartExist = false;
        Boolean ifVIP = false;
        User user;
        try {
            user = userMapper.selectByPrimaryKey(uid);
            ifUidExist = true;
        }catch (NullPointerException nullPointerException)
        {
            return false;
        }

        Integer[] userRole = {};
        try {
            userRole = userRoleMapper.getRolesById(uid);
            for (Integer integer : userRole) {
                if (integer == 2) {
                    ifVIP = true;
                    break;
                }
            }
        }catch (NullPointerException nullPointerException){
            ifVIP = false;
        }

        BookInfo bookinfo = new BookInfo();
        try {
            bookinfo = bookInfoMapper.selectByPrimaryKey((long)bookId);
            ifBookExist = true;
        }catch (NullPointerException nullPointerException)
        {
            return false;
        }

        ArrayList<Cart> carts = new ArrayList<>();
        try {
            carts = cartMapper.selectByUid(uid);
            ifCartExist = carts.size() != 0;

        }catch (NullPointerException nullPointerException){
            ifCartExist = false;
        }

        if (ifCartExist){
            //该用户的购物车已经存在
            System.out.println("Cart exist");
            //Step1-购物车内搜索该书籍，若没有，则添加，若有，则添加数量
//            Iterator<Cart> cartIterator = carts.iterator();
//            while (cartIterator.hasNext()){
//                Cart tempCart = cartIterator.next();
//            }
            Boolean bookExist = false;
            for (Cart tempCart : carts) {
                if (tempCart.getBookId().equals(bookId)){
                    System.out.println("book exist");
                    bookExist = true;
                    if (tempCart.getCount() < count){
                        System.out.println("book not enough");
                        return false;
                    }
                    else if (tempCart.getCount() == count){
                        cartMapper.deleteByPrimaryKey(tempCart.getCartId());
                        return true;
                    }
                    tempCart.setCount(tempCart.getCount() - count);
                    tempCart.setUpdateTime(new Date());
                    cartMapper.updateByPrimaryKey(tempCart);
                    break;
                }
            }
            if (!bookExist) {
                System.out.println("book do not exist");
                return false;
            }
        }else {
            // 该用户的购物车暂时不存在, 所以无法删除
            return false;
        }

        //更新该用户的所有的total
        float total = 0;
        for (Cart eachCart : carts){
            total += eachCart.getCount() * eachCart.getUnitPrice().floatValue();
        }
        for (Cart eachCart : carts){
            eachCart.setTotalMoney(total);
            cartMapper.updateByPrimaryKey(eachCart);
        }

        return true;
    }

    @Override
    public ArrayList<Cart> searchByUID(int uid) {
        return cartMapper.selectByUid(uid);
    }

    @Override
    public ArrayList<ArrayList<String>> searchNU(ArrayList<Long> bookId) {
        ArrayList<ArrayList<String>> NU = new ArrayList<>();
        for (Long tempBookId : bookId){
            String bookName = bookInfoMapper.selectByPrimaryKey((long)tempBookId).getName();
            String bookURL = bookInfoMapper.selectByPrimaryKey((long)tempBookId).getImageUrl();
            ArrayList<String> tempArraylist = new ArrayList<>();
            tempArraylist.add(bookName);
            tempArraylist.add(bookURL);
            NU.add(tempArraylist);
        }
        return NU;
    }

    @Override
    public OrderDetail directPay(int uid, Long bookId, int count) {
        //Order 表
        Orders newOrder = new Orders();
        BookInfo thisBook = bookInfoMapper.selectByPrimaryKey((long)bookId);

        newOrder.setOrderId(String.valueOf(ordersMapper.selectAll().size() - 1));
        System.out.println("New order id: " + newOrder.getOrderId());
        newOrder.setUserId(uid);
        newOrder.setPayment(String.valueOf(thisBook.getPrice().floatValue() * count));
        newOrder.setCreateTime(new Date());
        newOrder.setUpdateTime(new Date());
        newOrder.setStatus(0);
        ordersMapper.insert(newOrder);

        //OrderDetail 表
        OrderDetail newOrderDetail = new OrderDetail();
        OrderDetail lastOrderDetail = orderDetailMapper.selectAll().get(orderDetailMapper.selectAll().size() - 1);
        newOrderDetail.setOrderDetailId(lastOrderDetail.getOrderDetailId() + 1);
        System.out.println("New detailed order id is :" + newOrderDetail.getOrderDetailId());
        newOrderDetail.setOrderId(newOrder.getOrderId());
        newOrderDetail.setBookId((long)bookId);
        newOrderDetail.setMount(1);
        newOrderDetail.setUnitPrice(thisBook.getPrice());
        newOrderDetail.setTotalPrice(BigDecimal.valueOf(thisBook.getPrice().floatValue() * count));
        orderDetailMapper.insert(newOrderDetail);

        thisBook.setDealMount(thisBook.getDealMount() + count);
        bookInfoMapper.updateByPrimaryKey(thisBook);

        return newOrderDetail;
    }

    @Override
    public ArrayList<OrderDetail> payWithCart(ArrayList<Integer> cartIds) {
        ArrayList<OrderDetail> orderDetailArrayList = new ArrayList<>();
        for (Integer cartId : cartIds) {
            Cart thisCart = cartMapper.selectByPrimaryKey(cartId);
            orderDetailArrayList.add(directPay(thisCart.getUid(), thisCart.getBookId(), thisCart.getCount()));
            cartMapper.deleteByPrimaryKey(cartId);
        }
        return orderDetailArrayList;
    }

    @Override
    public void updateTotal() {
        HashSet<Integer> userSet = new HashSet<>();
        ArrayList<Cart> allCarts = cartMapper.selectAll();
        //首先生成一个集合，包含所有uid
        for (Cart tempCart : allCarts){
            userSet.add(tempCart.getUid());
        }
        //遍历所有uid，赋值所有的total
        for (int uid : userSet) {
            float total = 0;
            ArrayList<Cart> carts = new ArrayList<>();
            carts = cartMapper.selectByUid(uid);
            for (Cart eachCart : carts){
                total += eachCart.getCount() * eachCart.getUnitPrice().floatValue();
            }
            for (Cart eachCart : carts){
                eachCart.setTotalMoney(total);
                cartMapper.updateByPrimaryKey(eachCart);
            }
        }

    }
}
